﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SendMessageFromThread;
using System.Data.SqlClient;

namespace 生产计划批量打印工具
{
    public partial class frmContractToPlan : Form
    {
        SqlTools.SqlTools sqt_order;
        SqlTools.SqlTools sqt_jh;

        string strConnectionString_order = "Data Source=@ServerAddress;Initial Catalog=TPAMain;Persist Security Info=True;User ID=sa;Password=856518armyman";
        string strConnectionString_jh = "Data Source=@ServerAddress;Initial Catalog=@DatabaseName;Persist Security Info=True;User ID=sa;Password=856518armyman";
        string strDefaultSelectStringA = "select hta001 订单编号,hta011 合同号,hta029 验收方式,hta020 开票形式,hta026 生产车间 from hta_table where hta014='Y' and hta001 in (select htb001 from htb_table where htb016<htb006 and htb006>0 and htb003 like '@型号限制') and hta026='@生产车间'";
        string strDefualtSelectStringB= "select htb002 订单项次,htb003 型号规格,ycl002 产品名称,ycl008 单位,htb006-htb016 未生产计划数量,htb010 交货日期 from htb_table left join ycl_table on htb003=ycl001 where htb001='@HTNo' and htb016<htb006 and htb006>0 order by htb002";
        string strGetMAXJHID = "select max(jha001) 最大计划单号 from scjha_table where jha002=CONVERT(varchar(100), GETDATE(), 112)";
        string strGetServerDate = "select CONVERT(varchar(100), GETDATE(), 112)";
        string strGetOperatorInfo = "select yh001 操作员ID,yh002 操作员名称,yh003 部门ID,yh004 部门名称 from yh_table where yh001='@OperatorID'";
        string strInsertScjha = "insert into scjha_table (jha001,jha002,jha003,jha004,jha005,jha006,jha007,jha008,jha009,jha010,jha011,jha014,jha015,jha016,jha017,jha018,jha020,jha021) values ('@计划编号','@计划日期','@操作员ID','@操作员名称','@部门ID','@部门名称','Y','@操作员ID',getdate(),'@操作员ID',getdate(),'@生产车间','','@开票形式','@验收方式','YBL','','生产计划')";
        string strInsertScjhb = "insert into scjhb_table (jhb001,jhb002,jhb003,jhb004,jhb005,jhb006,jhb007,jhb008,jhb009,jhb010,jhb011,jhb012,jhb013,jhb014,jhb015,jhb016,jhb017,jhb018,jhb020,jhb021,jhb022,jhb023,jhb024,bChecked) select '@计划编号',ROW_NUMBER () over(order by htb002) ,htb001,htb002,htb003,htb004,htb005,htb006-htb016,htb010,'订单转生产计划','Y',0,0,0,'','','','S','YBL',0,'普通','一般类','@合同号',0 from TPAMain.dbo.htb_table where htb001='@订单编号' and htb006-htb016>0";
        string strUpdateHTSL = "update htb_table set htb016=htb006 where htb001='@订单编号'";
        string strUpdateScjha_es = "update scjha_table set jha020='二筛合同' from scjhb_table,hta_table ,htc_table where jha001=jhb001 and jhb003=hta001 and hta001=htc001 and (hta021='二筛' or htc002 like '%合同为二筛合同%' or htc002 like '%二次筛选补充合同%' or htc002 like '%合同为筛选合同%')";
        string strUpdateScjhb_es = "update scjhb_table set jhb013=jhb008 from hta_table ,htc_table where jhb003=hta001 and hta001=htc001 and (hta021='二筛' or htc002 like '%合同为二筛合同%' or htc002 like '%二次筛选补充合同%' or htc002 like '%合同为筛选合同%')";
        string strUpdateHtb_es = "update htb_table set htb018=htb006 from hta_table ,htc_table,scjhb_table where htb001=jhb003 and htb002=jhb004 and jhb003=hta001 and hta001=htc001 and (hta021='二筛' or htc002 like '%合同为二筛合同%' or htc002 like '%二次筛选补充合同%' or htc002 like '%合同为筛选合同%')";

        string strOperatorID;
        string strOperatorName;
        string strDepartmentID;
        string strDepartmentName;
        string strFactoryName;

        public frmContractToPlan(string strTmpFactoryName)
        {
            InitializeComponent();
            strFactoryName = strTmpFactoryName;
            strDefaultSelectStringA = strDefaultSelectStringA.Replace("@生产车间", strFactoryName);
            switch (strFactoryName)
            {
                case "601车间":
                case "微波车间":
                    strConnectionString_jh = strConnectionString_jh.Replace("@DatabaseName", "TPAMainTZ");
                    break;
                case "603车间":
                    strConnectionString_jh = strConnectionString_jh.Replace("@DatabaseName", "TPAMain");
                    break;
            }
        }

        private void rbtn1_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtn1.Checked)
            {
                rbtn2.Checked = false;
                rbtn3.Checked = false;
                rbtn4.Checked = false;
            }
        }

        private void rbtn2_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtn2.Checked)
            {
                rbtn1.Checked = false;
                rbtn3.Checked = false;
                rbtn4.Checked = false;
            }
            txtContractNo.Enabled = rbtn2.Checked ;
        }

        private void rbtn3_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtn3.Checked)
            {
                rbtn1.Checked = false;
                rbtn2.Checked = false;
                rbtn4.Checked = false;
            }
            txtContractID.Enabled = rbtn3.Checked;
        }

        private void rbtn4_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtn4.Checked)
            {
                rbtn1.Checked = false;
                rbtn2.Checked = false;
                rbtn3.Checked = false;
            }
            dtpDateFrom.Enabled = rbtn4.Checked;
            dtpDateTo.Enabled = rbtn4.Checked;
        }

        private void frmContractToPlan_Load(object sender, EventArgs e)
        {
            strConnectionString_order = strConnectionString_order.Replace("@ServerAddress", 生产计划批量打印工具.Properties.Settings.Default.ServerAddress);
            strConnectionString_jh = strConnectionString_jh.Replace("@ServerAddress", 生产计划批量打印工具.Properties.Settings.Default.ServerAddress);
            sqt_order = new SqlTools.SqlTools(strConnectionString_order);
            sqt_jh = new SqlTools.SqlTools(strConnectionString_jh);
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            int iWorkMode = 0;
            string strSelectString = strDefaultSelectStringA;
            switch (strFactoryName)
            {
                case "601车间":
                case "603车间":
                    strSelectString = strSelectString.Replace("@型号限制", "%");
                    break;
                case "微波车间":
                    strSelectString = strSelectString.Replace("@型号限制", "%");
                    break;
            }
            if (rbtn1.Checked)
            {
                iWorkMode = 0;
            }
            if (rbtn2.Checked)
            {
                iWorkMode = 1;
            }
            if (rbtn3.Checked)
            {
                iWorkMode = 2;
            }
            if (rbtn4.Checked)
            {
                iWorkMode = 3;
            }
            switch (iWorkMode)
            {
                case 1:
                    if (txtContractNo .Text .Trim().Length == 0)
                    {
                        MessageBox.Show("合同号不能为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtContractNo.Focus();
                        return;
                    }
                    strSelectString += " and hta011 like '" + txtContractNo.Text.Trim() + "'";
                    break;
                case 2:
                    if (txtContractID.Text.Trim().Length == 0)
                    {
                        MessageBox.Show("订单编号不能为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtContractID.Focus();
                        return;
                    }
                    strSelectString += " and hta001='" + txtContractID.Text .Trim () + "'";
                    break;
                case 3:
                    strSelectString += " and hta002 between '" + dtpDateFrom.Value.ToString("yyyyMMdd") + "' and '" + dtpDateTo.Value.ToString("yyyyMMdd")+"'";
                    break;
            }
            dgv1.DataSource = sqt_order.GetDataTable(strSelectString);
            dgv1.Sort(dgv1.Columns["订单编号"], ListSortDirection.Ascending);
            dgv1.AutoResizeColumns();
            if (dgv1.Rows.Count > 0)
            {
                dgv1.CurrentCell = dgv1.Rows[0].Cells[0];
            }
        }

        private void dgv1_CurrentCellChanged(object sender, EventArgs e)
        {
            if (dgv1.CurrentRow != null)
            {
                if (GetString(dgv1.CurrentRow.Cells["订单编号"].Value).Length > 0)
                {
                    string strTmpSelectString = strDefualtSelectStringB;
                    switch (strFactoryName)
                    {
                        case "601车间":
                        case "603车间":
                            strTmpSelectString = strTmpSelectString.Replace("@型号限制", "%");
                            break;
                        case "微波车间":
                            strTmpSelectString = strTmpSelectString.Replace("@型号限制", "%");
                            break;
                        default:
                            strTmpSelectString = strTmpSelectString.Replace("@型号限制", "%");
                            break;
                    }
                    dgv2.DataSource = sqt_order.GetDataTable(strTmpSelectString.Replace("@HTNo", GetString(dgv1.CurrentRow.Cells["订单编号"].Value)));
                    dgv2.AutoResizeColumns();
                }
            }
            else
            {
                dgv2.DataSource = null;
            }
        }

        private string GetCurrentJHID()
        {
            //string strID = string.Empty;
            //SqlConnection conn = sqt_jh.GetConnection();
            //SqlCommand cmd = new SqlCommand("GetID", conn);
            //cmd.CommandType = CommandType.StoredProcedure;
            //cmd.Parameters.AddWithValue("@sModName", "pm_scjh");
            //cmd.Parameters.Add("@rval", SqlDbType.VarChar, 50);
            //cmd.Parameters["@rval"].Direction = ParameterDirection.Output;
            //try
            //{
            //    sqt_jh.OpenConnection(conn);
            //    while (strID.Equals(string.Empty))
            //    {
            //        cmd.ExecuteNonQuery();
            //        strID =GetString (cmd.Parameters["@rval"].Value);
            //    }
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show("获取新生产计划编号时发生错误：" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return string.Empty ;
            //}
            //finally
            //{
            //    sqt_jh.CloseConnection(conn);
            //}
            //return strID;
            string strMaxID = GetString(sqt_jh.DoCmdScalarData(strGetMAXJHID));
            if (strMaxID == string.Empty)
            {
                return GetServerDate() + "0001";
            }
            else
            {
                if (strMaxID.Length > 12)
                {
                    return strMaxID.Substring(0, 8) + "0001";
                }
                else
                {
                    int iTmpID = GetInt(strMaxID.Substring(8, 4)) + 1;
                    return strMaxID.Substring(0, 8) + iTmpID.ToString("0000");
                }
            }
        }

        private string GetServerDate()
        {
            string strServerDate = GetString(sqt_order.DoCmdScalarData(strGetServerDate));
            return strServerDate;
        }

        private void GetOperatorInfo()
        {
            strOperatorID =string.Empty ;
            strOperatorName =string.Empty ;
            strDepartmentID =string.Empty ;
            strDepartmentName =string.Empty ;
            if (txtOperatorID.Text .Trim ().Length ==0)
            {
                return ;
            }
            DataTable tmpdt = sqt_jh.GetDataTable(strGetOperatorInfo.Replace("@OperatorID", txtOperatorID.Text.Trim()));
            if (tmpdt.Rows.Count == 0)
            {
                return;
            }
            else
            {
                strOperatorID = GetString(tmpdt.Rows[0]["操作员ID"]);
                strOperatorName = GetString(tmpdt.Rows[0]["操作员名称"]);
                strDepartmentID = GetString(tmpdt.Rows[0]["部门ID"]);
                strDepartmentName = GetString(tmpdt.Rows[0]["部门名称"]);
            }
        }

        private string GetString(object tmpobj)
        {
            try
            {
                return tmpobj.ToString().Trim();
            }
            catch
            {
                return string.Empty;
            }
        }

        private int GetInt(object tmpobj)
        {
            try
            {
                return Convert .ToInt32 ( tmpobj);
            }
            catch
            {
                return 0;
            }
        }

        private void btnConversion_Click(object sender, EventArgs e)
        {
            List<string> jhids = new List<string>();        //新增生产计划编号清单
            GetOperatorInfo();
            if (dgv1.Rows.Count == 0)
            {
                MessageBox.Show("没有可供操作的记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (chkOnlySelected.Checked && dgv1.SelectedRows.Count == 0)
            {
                MessageBox.Show("没有可供操作的记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (txtOperatorID.Text.Trim().Length == 0)
            {
                MessageBox.Show("操作员ID必须填写！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtOperatorID.Focus();
                return;
            }
            DataTable tmpdtHeader = new DataTable();
            tmpdtHeader.Columns.Add("订单编号");
            tmpdtHeader.Columns.Add("合同号");
            tmpdtHeader.Columns.Add("验收方式");
            tmpdtHeader.Columns.Add("开票形式");
            tmpdtHeader.Columns.Add("生产车间");
            DataRow dr;
            if (chkOnlySelected.Checked)
            {
                for (int i = 0; i < dgv1.SelectedRows.Count; i++)
                {
                    dr = tmpdtHeader.NewRow();
                    dr["订单编号"] = dgv1.SelectedRows[i].Cells["订单编号"].Value;
                    dr["合同号"] = dgv1.SelectedRows[i].Cells["合同号"].Value;
                    dr["验收方式"] = dgv1.SelectedRows[i].Cells["验收方式"].Value;
                    dr["开票形式"] = dgv1.SelectedRows[i].Cells["开票形式"].Value;
                    if (GetString(dgv1.SelectedRows[i].Cells["生产车间"].Value).Length == 0)
                    {
                        dr["生产车间"] = "603车间";
                    }
                    else
                    {
                        dr["生产车间"] = dgv1.SelectedRows[i].Cells["生产车间"].Value;
                    }
                    tmpdtHeader.Rows.Add(dr);
                }
            }
            else
            {
                for (int i = 0; i < dgv1.Rows.Count; i++)
                {
                    dr = tmpdtHeader.NewRow();
                    dr["订单编号"] = dgv1.Rows[i].Cells["订单编号"].Value;
                    dr["合同号"] = dgv1.Rows[i].Cells["合同号"].Value;
                    dr["验收方式"] = dgv1.Rows[i].Cells["验收方式"].Value;
                    dr["开票形式"] = dgv1.Rows[i].Cells["开票形式"].Value;
                    dr["生产车间"] = dgv1.Rows[i].Cells["生产车间"].Value;
                    tmpdtHeader.Rows.Add(dr);
                }
            }
            if (tmpdtHeader.Rows.Count == 0)
            {
                MessageBox.Show("没有可供操作的记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            progressBar1.Maximum = tmpdtHeader.Rows.Count;
            for (int i = 0; i < tmpdtHeader.Rows.Count; i++)
            {
                SendMessageFromThread.SetProgressFromThread spft = new SetProgressFromThread(progressBar1);
                spft.SetProgress(i + 1);
                DataTable tmpdtBody = sqt_order.GetDataTable(strDefualtSelectStringB.Replace("@HTNo", tmpdtHeader.Rows[i]["订单编号"].ToString()));
                if (tmpdtBody.Rows.Count == 0)
                {
                    continue;
                }
                string strJHID = GetCurrentJHID();
                string strTmpInsertA = strInsertScjha.Replace("@计划编号", strJHID)
                                                                        .Replace("@计划日期", strJHID.Substring(0, 8))
                                                                        .Replace("@操作员ID", strOperatorID)
                                                                        .Replace("@操作员名称", strOperatorName)
                                                                        .Replace("@部门ID", strDepartmentID)
                                                                        .Replace("@部门名称", strDepartmentName)
                                                                        .Replace("@生产车间", tmpdtHeader.Rows[i]["生产车间"].ToString())
                                                                        .Replace("@开票形式", tmpdtHeader.Rows[i]["开票形式"].ToString())
                                                                        .Replace("@验收方式", tmpdtHeader.Rows[i]["验收方式"].ToString());
                sqt_jh.DoCmdExecuteNonQuery(strTmpInsertA);
                sqt_jh.DoCmdExecuteNonQuery(strInsertScjhb.Replace("@计划编号", strJHID)
                                                                                            .Replace("@合同号", GetString(tmpdtHeader.Rows[i]["合同号"]))
                                                                                            .Replace("@订单编号", GetString(tmpdtHeader.Rows[i]["订单编号"])));
                sqt_order.DoCmdExecuteNonQuery(strUpdateHTSL.Replace("@订单编号", GetString(tmpdtHeader.Rows[i]["订单编号"])));
                jhids.Add(strJHID);
            }
            //在新增计划中检查哪些是二筛合同的，去除欠交，同时备注二筛合同
            string strTmpUpdateJha = strUpdateScjha_es;
            string strTmpUpdateJhb = strUpdateScjhb_es;
            string strTmpUpdateHtb = strUpdateHtb_es;
            for (int i=0;i<jhids.Count;i++)
            {
                if (i==0)
                {
                    strTmpUpdateJha += " and (";
                    strTmpUpdateJhb += " and (";
                    strTmpUpdateHtb += " and (";
                }
                strTmpUpdateJha += " jhb001='" + jhids[i] + "' or ";
                strTmpUpdateJhb += " jhb001='" + jhids[i] + "' or ";
                strTmpUpdateHtb += " jhb001='" + jhids[i] + "' or ";
                if (i==jhids.Count -1)
                {
                    strTmpUpdateJha += " )";
                    strTmpUpdateJhb += " )";
                    strTmpUpdateHtb += " )";
                }
            }
            sqt_jh.DoCmdExecuteNonQuery(strTmpUpdateJha);
            sqt_jh.DoCmdExecuteNonQuery(strTmpUpdateJhb);
            sqt_order.DoCmdExecuteNonQuery(strTmpUpdateHtb);
            MessageBox.Show("转换完毕！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            btnSearch_Click(this, new EventArgs());
        }

        private void dgv1_SelectionChanged(object sender, EventArgs e)
        {
            if (dgv1.Rows.Count > 0)
            {
                tsslMessage.Text = "共" + dgv1.Rows.Count.ToString() + "个合同，已选定" + dgv1.SelectedRows.Count.ToString() + "个合同。";
            }
            else
            {
                tsslMessage.Text = string.Empty;
            }
        }

        private void frmContractToPlan_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.Owner.Show();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            生产计划批量打印工具.Properties.Settings.Default.Operator = txtOperatorID.Text;
            生产计划批量打印工具.Properties.Settings.Default.Save();
        }
    }
}
